package com.jinkaimen.kqb.ui.fragment.centraldocument;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseFragment;
import com.ht.baselibs.ui.widget.LoadingLayout;
import com.ht.baselibs.utils.DateUtils;
import com.ht.baselibs.utils.NetUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.bean.Moment;
import com.jinkaimen.kqb.bean.hss.CenterDocumentBean;
import com.jinkaimen.kqb.manager.ApiManager;
import com.jinkaimen.kqb.ui.weiget.TextMoreTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.imageloader.BGAImage;
import cn.bingoogolapple.photopicker.imageloader.BGAImageLoader;
import cn.bingoogolapple.photopicker.util.BGAAsyncTask;
import cn.bingoogolapple.photopicker.util.BGAPhotoPickerUtil;
import cn.bingoogolapple.photopicker.util.BGASavePhotoTask;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Response;

public class MarketingFragment extends BaseFragment implements BGANinePhotoLayout.Delegate, EasyPermissions.PermissionCallbacks, BGAAsyncTask.Callback<Void> {
    private static final int REQUEST_CODE_PERMISSION_PHOTO_PREVIEW = 1;

    private static final int REQUEST_CODE_ADD_MOMENT = 1;

    private ListView listView;
    private BGASavePhotoTask mSavePhotoTask;

    private BGANinePhotoLayout mCurrentClickNpl;
    private List<Moment> moments;
    File downloadDir = new File(Environment.getExternalStorageDirectory(), "HSS");

    Stack stack = new Stack();
    private MyListAdpter myListAdpter;
    private LoadingLayout loadingLayout;
    private SmartRefreshLayout pLvMemberManager;
    private int currentPage;


    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {

    }

    @Override
    protected View initContentView() {
        return LayoutInflater.from(mContext).inflate(R.layout.frag_central_document, null);
    }

    @Override
    protected void initChildView() {
        listView = findViewById(R.id.recy_central_document_frag);
        pLvMemberManager = findViewById(R.id.plv_activity_member_manager);
        pLvMemberManager.setRefreshFooter(new ClassicsFooter(mContext).setSpinnerStyle(SpinnerStyle.Scale));
        loadingLayout = findViewById(R.id.loading_layout);
        moments = new ArrayList<>();
        currentPage = 1;
        addNetImageTestData();
        myListAdpter = new MyListAdpter(mContext, moments);
        listView.setAdapter(myListAdpter);
        loadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingLayout.setStatus(LoadingLayout.Loading);
                currentPage = 1;
                addNetImageTestData();
            }
        });
        pLvMemberManager.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                currentPage = 1;
                if (!NetUtils.isNetWorkConnection()) {
                    UIUtils.showToast("请检查您的网络设置");
                    return;
                }
                //pLvMemberManager.resetHasMore();
                pLvMemberManager.setLoadmoreFinished(false);
                currentPage = 1;
                addNetImageTestData();
            }
        });
        pLvMemberManager.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                currentPage++;
                addNetImageTestData();
            }
        });
    }

    @Override
    protected void load() {


    }

    /**
     * 添加网络图片测试数据
     */
    private void addNetImageTestData() {
        loadingLayout.setStatus(LoadingLayout.Loading);
        ApiManager.getApi().getCenterPic(
                "HSS001012",
                currentPage,
                10).enqueue(new NetCallBack<CenterDocumentBean>() {
            @Override
            protected void onSuccess(Call<CenterDocumentBean> call, Response<CenterDocumentBean> response) {
                if (currentPage == 1) {
                    moments.clear();
                }
                if (response != null && response.body() != null) {
                    loadingLayout.setStatus(LoadingLayout.Success);
                    CenterDocumentBean centerDocumentBean = response.body();
                    String content;
                    ArrayList<String> orgUrls;
                    long time;
                    String timeHMS;
                    for (int i = 0; i < centerDocumentBean.records.size(); i++) {
                        content = centerDocumentBean.records.get(i).content;
                        orgUrls = centerDocumentBean.records.get(i).orgUrls;
                        time = centerDocumentBean.records.get(i).createTime.time;
                        timeHMS = DateUtils.formatDateTimeHMS(time);
                        moments.add(new Moment(content, orgUrls, timeHMS));
                    }
                    if (myListAdpter != null) {
//                        myListAdpter.notifyDataSetChanged();
                    }
                } else {
                    loadingLayout.setStatus(LoadingLayout.Empty);
                }

            }

            @Override
            protected void hiddenProgress() {
                if (currentPage == 1) {
                    pLvMemberManager.finishRefresh();
                } else {
                    pLvMemberManager.finishLoadmore();
                }

            }

            @Override
            public void onFailure(Call<CenterDocumentBean> call, Throwable t) {
                super.onFailure(call, t);
                loadingLayout.setStatus(LoadingLayout.Error);
            }

        });
    }

    @Override
    protected void setChildViewListener() {

    }

    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        mCurrentClickNpl = ninePhotoLayout;
        photoPreviewWrapper();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PREVIEW) {
            Toast.makeText(mContext, "您拒绝了「图片预览」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPostExecute(Void aVoid) {
        mSavePhotoTask = null;
        if (stack != null && !stack.isEmpty()) {
            savePic((String) stack.pop());
        } else {
            UIUtils.showToast("保存成功");
        }
    }

    @Override
    public void onTaskCancelled() {
        mSavePhotoTask = null;

    }

    @Override
    public void onDestroy() {
        if (mSavePhotoTask != null) {
            mSavePhotoTask.cancelTask();
            mSavePhotoTask = null;
        }
        super.onDestroy();
    }

    private synchronized void savePic(final String url) {
        if (mSavePhotoTask != null) {
            return;
        }
        File file;
        if (url.startsWith("file")) {
            file = new File(url.replace("file://", ""));
            if (file.exists()) {
                UIUtils.showToast("");
                return;
            }
        }

        // 通过MD5加密url生成文件名，避免多次保存同一张图片
        file = new File(downloadDir, BGAPhotoPickerUtil.md5(url) + ".png");
        if (file.exists()) {
            UIUtils.showToast("图片已存在");
            return;
        }

        mSavePhotoTask = new BGASavePhotoTask(this, mContext, file);


        BGAImage.download(url, new BGAImageLoader.DownloadDelegate() {
            @Override
            public void onSuccess(String url, Bitmap bitmap) {
                mSavePhotoTask.setBitmapAndPerform(bitmap);

            }

            @Override
            public void onFailed(String url) {
                mSavePhotoTask = null;
                BGAPhotoPickerUtil.show(R.string.bga_pp_save_img_failure);
            }
        });
    }


    class MyListAdpter extends BaseAdapter {
        Context con;
        TextMoreTextView tv;
        List<Moment> data;

        public MyListAdpter(Context con, List<Moment> data) {
            this.con = con;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        // HashMap<Integer, View> hashM = new HashMap<Integer, View>();

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder = null;
            View view;
            //  if (hashM.get(position) == null) {
            holder = new Holder();
            view = LayoutInflater.from(con).inflate(R.layout.item_central_document,
                    null);
            holder.tv = (TextMoreTextView) view
                    .findViewById(R.id.tv_item_central_document_copy_text);

            holder.saveImgBtn = (Button) view.findViewById(R.id.btn_item_central_document_save_img);
            holder.copyTextBtn = (Button) view.findViewById(R.id.btn_item_central_document_copy_text);
            holder.mTvTimeDay = (TextView) view.findViewById(R.id.tv_time_day);
            holder.mTvTimeMonth = (TextView) view.findViewById(R.id.tv_time_month);
            holder.mTvTimeHour = (TextView) view.findViewById(R.id.tv_time_hour);
            holder.ninePhotoLayout = (BGANinePhotoLayout) view.findViewById(R.id.npl_item_moment_photos);
            holder.saveImgBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (stack != null) {
                        stack.clear();
                    }
                    ArrayList<String> photos = moments.get(position).photos;
                    for (String photo : photos) {
                        stack.push(photo);
                    }
                    if (photos.size() > 0) {
                        UIUtils.showToast("正在保存...");
                        savePic(photos.get(0));
                        stack.remove(0);
                    }
                }
            });
            holder.copyTextBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    cm.setText(moments.get(position).content);
                    UIUtils.showToast("已复制");
                }
            });
            view.setTag(holder);
            // hashM.put(position, view);
//            } else {
//              //  view = hashM.get(position);
//                holder = (Holder) view.getTag();
//            }
            holder.ninePhotoLayout.setDelegate(MarketingFragment.this);
            holder.ninePhotoLayout.setData(data.get(position).photos);
            holder.tv.setDesc(data.get(position).content, holder.tv, TextView.BufferType.NORMAL);
            String time = data.get(position).time;
            if (!TextUtils.isEmpty(time)) {
                String day = time.substring(6, 8);
                String month = time.substring(3, 5);
                String hour = time.substring(8, 14);
                holder.mTvTimeDay.setText(day);
                holder.mTvTimeMonth.setText(month + "月");
                holder.mTvTimeHour.setText(hour);
            }
            return view;
        }

        class Holder {
            TextMoreTextView tv;
            BGANinePhotoLayout ninePhotoLayout;
            Button saveImgBtn;
            Button copyTextBtn;
            TextView mTvTimeDay, mTvTimeMonth, mTvTimeHour;
        }
    }

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }
        // 保存图片的目录，改成你自己要保存图片的目录。如果不传递该参数的话就不会显示右上角的保存按钮

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            if (mCurrentClickNpl.getItemCount() == 1) {
                // 预览单张图片

                startActivity(BGAPhotoPreviewActivity.newIntent(mContext, downloadDir, mCurrentClickNpl.getCurrentClickItem()));
            } else if (mCurrentClickNpl.getItemCount() > 1) {
                // 预览多张图片

                startActivity(BGAPhotoPreviewActivity.newIntent(mContext, downloadDir, mCurrentClickNpl.getData(), mCurrentClickNpl.getCurrentClickItemPosition()));
            }
        } else {
            EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PREVIEW, perms);
        }
    }

}
